<template>
    <el-calendar v-model="value">
        <template #date-cell="{ data }">
            <div style="width: 100%;height: 100%;" @click="SettingTodo(data.day)">
                <div>{{ data.day }}</div>
                <div>{{ read(data.day) }}</div>
            </div>
        </template>
    </el-calendar>
    <el-dialog v-model="dialogFormVisible" title="添加代办项" width="30%" draggable="true">
        <el-form :model="form" ref="formRef">
            <el-form-item label="要做的事情" lable-width="90px" prop="todo">
                <el-input v-model="form.Todo" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="Cancel(formRef)">Cancel</el-button>
                <el-button type="primary" @click="Submit(formRef)">Confirm</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { Ref, ref, onMounted } from 'vue'
import type { FormInstance } from 'element-plus';
import { addCale, editCale, getCales } from '../../http/index'
import Calendar from '../../class/Cale'
const value = ref(new Date())
const dialogFormVisible = ref(false)
const form = ref(({
    Day: "",
    Todo: ""
}))
const formRef = ref<FormInstance>()
const SettingTodo = (day: string) => {
    form.value.Day = day
    form.value.Todo = read(day)
    dialogFormVisible.value = true
}
//历史数据(数据库的)
const tolist: Ref<Array<Calendar>> = ref<Array<Calendar>>([])
const load = async () => {
    var res = await getCales("") as any
    tolist.value = res
}
onMounted(async () => { await load() })

const read = (day: string): string => {
    return tolist.value?.find(f => f.Day == day)?.Todo!
}

const Cancel = (formRef: FormInstance | undefined) => {
    dialogFormVisible.value = false
    formRef?.resetFields() //表单重置
}
const Submit = async (formRef: FormInstance | undefined) => {
    //获取当前是否存在这个代办项
    let todo = read(form.value.Day)
    // 不存在则添加，否则更新
    if (!todo) {
        await addCale({
            day: form.value.Day,
            todo: form.value.Todo
        })
    } else {
        await editCale({
            day: form.value.Day,
            todo: form.value.Todo
        })
    }
    await load()
    dialogFormVisible.value = false
    formRef?.resetFields()
}
</script>